/**
 * 箱包报表
 */

import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import React, { useState, useRef, useCallback, useEffect } from 'react';
import { useRequest } from '@umijs/hooks';
import { Button, Input, DatePicker, message } from 'antd';
import ProTable from '@ant-design/pro-table';
import styles from './bagReportIndex.less';
import moment from 'moment';
import router from 'umi/router';
import { fileDownload } from '@/utils/downExcel';

import {
  pkgManageReport,
  pkgManageReportExport
} from '../service';

import AuthComponent from '@/components/Authorized/AuthComponent';

class PrivateData {
  static toolBarRenderArr = [
    { text: '导出', value: '1', authCode: ['banksearchSystem.BagReport.export'], disabled: false },
  ];
  static format = 'YYYY-MM-DD';
  // 航班号处理
  static formatFlightNo = val => {
    if (!val) {
      return '';
    } else if (val.length < 3 || /^\D/.test(val)) {
      return ''.toUpperCase.call(val);
    } else if (/^\d{2}/.test(val)) {
      return `3U${val}`;
    } else {
      return val;
    }
  };
}

const BagReport = () => {

  const actionRef = useRef();
  const ref = useRef();

  const [height, controlH] = useState(300); // table高度
  const [isCollapse, controlC] = useState(true);
  const [selectedRowKeys, setSelectedRowKeys] = useState([]); // 勾选索引
  const [selectedRows, setSelectedRows] = useState([]); // 勾选列

  const [createStartTime, setCreateStartTime] = useState(moment().format(PrivateData.format)); // 航班开始时间
  const [createEndTime, setCreateEndTime] = useState(moment().format(PrivateData.format)); // 航班结束时间

  const [searchData, setSearchData] = useState({});

  // 表格是否有数据
  const [exportFlag, handleExportFlag] = useState(false);

  // 导出
  const { run: runPkgManageReportExport } = useRequest(params => pkgManageReportExport(params), {
    manual: true,
    onSuccess(res) {
      fileDownload(res, '箱包报表');
    }
  })

  useEffect(() => {
    if (isCollapse) {
      controlH(document.body.clientHeight - 370);
    } else {
      controlH(document.body.clientHeight - 470);
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [isCollapse]);

  // rowSelection
  const tableSelectChange = (selectedRowKeys, selectedRows) => {
    setSelectedRowKeys(selectedRowKeys);
    setSelectedRows(selectedRows);
  };
  const rowSelection = {
    selectedRowKeys,
    onChange: tableSelectChange,
  };

  const disabledStartDate = useCallback((current) => {
    if (createEndTime) return current && (current > moment().endOf('day') || current > moment(createEndTime).endOf('day'));
    return current && current > moment().endOf('day');
  }, [createEndTime]);

  const disabledEndDate = useCallback((current) => {
    if (createStartTime) return current && (current > moment().endOf('day') || current < moment(createStartTime).startOf('day'));
    return current && current > moment().endOf('day');
  }, [createStartTime]);

  // 顶部点击事件
  const headerTitleClick = useCallback(val => {
    if (val === '1' ) {
      if (!exportFlag) {
        message.warning('表格数据为空');
        return
      }
      runPkgManageReportExport({
        ...searchData
      });
    }
  }, [searchData, exportFlag])

  const columns = [
    {
      title: '事故单编号',
      dataIndex: 'accidentId',
      width: 120,
      hideInSearch: true,
    },
    {
      title: '服务航站',
      dataIndex: 'serviceCity',
      width: 100,
      hideInSearch: true,
    },
    {
      title: '航班日期',
      dataIndex: 'flightDate',
      width: 120,
      hideInSearch: true,
    },
    {
      title: '航班开始时间',
      dataIndex: 'flightStartTime',
      hideInTable: true,
      renderFormItem: (_, { onChange, value }) => {
        return (
          <DatePicker
            style={{ width: '100%' }}
            format={PrivateData.format}
            onChange={val => {
              setCreateStartTime(val);
              onChange(val);
            }}
            disabledDate={disabledStartDate}
            value={value ? value : moment()}
          />
        );
      }
    },
    {
      title: '航班结束时间',
      dataIndex: 'flightEndTime',
      hideInTable: true,
      renderFormItem: (_, { onChange, value }) => {
        return (
          <DatePicker
            style={{ width: '100%' }}
            format={PrivateData.format}
            onChange={val => {
              setCreateEndTime(val);
              onChange(val);
            }}
            disabledDate={disabledEndDate}
            value={value}
          />
        );
      }
    },
    {
      title: '航班号',
      dataIndex: 'flightNo',
      width: 80,
      renderFormItem: (_, { value, onChange }) => {
        return <Input
          onChange= {e => {
            let value = PrivateData.formatFlightNo(e.target.value);
            onChange(value);
          }}
          value={value}
          allowClear
          maxLength={6}
          placeholder="3U" />;
      }
    },
    {
      title: '机型',
      dataIndex: 'acType',
      width: 120,
    },
    {
      title: '机号',
      dataIndex: 'planeCode',
      width: 120,
      hideInSearch: true,
    },
    {
      title: '赔偿金额',
      dataIndex: 'payMoney',
      width: 120,
      hideInSearch: true,
    },
    {
      title: '新箱型号',
      dataIndex: 'pkgName',
      width: 160,
      hideInSearch: true,
    },
  ];

  return (
    <>
      <ProTable
        actionRef={actionRef}
        formRef={ref}
        className={styles.compactTable}
        rowKey="id"
        rowSelection={rowSelection}
        headerTitle="箱包报表"
        toolBarRender={() => PrivateData.toolBarRenderArr.map((item, index) => {
          if (AuthComponent.getAuth(item.authCode)) {
            return <Button
              type="primary"
              disabled={item.disabled}
              size="small"
              onClick={() => headerTitleClick(item.value)}>
              {item.text}
            </Button>;
          }
        })}
        postData={data => {
          if (data.length === 0) {
            handleExportFlag(false)
          } else {
            handleExportFlag(true)
          }
          return data
        }}
        request={params => {
          let arr = ['flightStartTime', 'flightEndTime'];
          for (let item of arr) {
            if (params[item] && params[item].isValid()) {
              params[item] = moment(params[item]).format(PrivateData.format)
            }
            if (item === 'flightStartTime') {
              params[item] = params[item] ? params[item] : moment().format(PrivateData.format)
            }
          }

          setSearchData(params);

          return pkgManageReport(params);
        }}
        tableAlertRender={false}
        columns={columns}
        options={false}
        pagination={{
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total, range) => `第${range[0]}-${range[1]}条 共 ${total} 项`,
        }}
        scroll={{ x: 900, y: height }}
        search={{
          onCollapse: val => {
            controlC(val);
          },
        }}
      >
      </ProTable>
    </>
  )
}

export default BagReport;
